package com.ruoyi.config;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.enums.ConnectDeviceTypeEnum;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.util.*;

@Slf4j
public class WebSocketUser {
  @Getter
  private LoginUser loginUser;
  private Map<String,List<Session>> sessions = new HashMap<>();

  public WebSocketUser(LoginUser loginUser) {
    this.loginUser = loginUser;
  }

  public void addSession(ConnectDeviceTypeEnum DeviceType,Session session) {
    if(sessions.get(DeviceType.getType()) == null){
      List<Session> list = new ArrayList<>();
      list.add(session);
      sessions.put(DeviceType.getType(),list);
      log.debug(loginUser.getUsername() + "初始化连接并添加成功,当前为" + DeviceType.getType() + "连接数为:" + sessions.get(DeviceType.getType()).size());
    }else{
      sessions.get(DeviceType.getType()).add(session);
      isOverSessionNumber(DeviceType);
      log.debug(loginUser.getUsername() + "新增连接并添加成功,当前为" + DeviceType.getType() + "连接数为:" + sessions.get(DeviceType.getType()).size());
    }
  }

  //检查是否超过了最大连接数量
  private void isOverSessionNumber(ConnectDeviceTypeEnum DeviceType){
    List<Session> list = sessions.get(DeviceType.getType());
    if(list != null){
      if(list.size() > 10){
        Session session = list.get(0);
        try {
          if(session.isOpen()){
            session.getBasicRemote().sendText("断开连接");
            session.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
        list.remove(0);//去掉最前面的那一个
        log.debug("已经去掉最老的那个连接,用户为:" + loginUser.getUsername());
      }else{
        log.debug("暂未超过最大连接数,用户为:" + loginUser.getUsername());
      }
    }
  }


  public boolean removeSession(Session session) {
    boolean removed = false;

    // 遍历Map中的所有List<Session>
    for (List<Session> sessionList : sessions.values()) {
      // 使用Iterator遍历List，这样可以安全地删除元素
      Iterator<Session> iterator = sessionList.iterator();
      while (iterator.hasNext()) {
        Session currentSession = iterator.next();
        if (currentSession.equals(session)) {
          // 找到了要删除的Session
          iterator.remove();
          removed = true;
        }
      }
    }
    log.debug("去掉了一个连接,用户为:" + loginUser.getUsername());
    return removed;
  }

  public boolean isEmpty() {
    return sessions.isEmpty();
  }

  public List<Session> getSessionList(ConnectDeviceTypeEnum type){
    return sessions.get(type.getType());
  }

  public int size(){
    int phone = sessions.get(ConnectDeviceTypeEnum.MOBILE.getType()) == null ? 0 : sessions.get(ConnectDeviceTypeEnum.MOBILE.getType()).size();
    int pc = sessions.get(ConnectDeviceTypeEnum.PC.getType()) == null ? 0 : sessions.get(ConnectDeviceTypeEnum.PC.getType()).size();
    return phone + pc;
  }
}
